<?php


namespace app\service;


use app\model\Admin;
use app\model\AdminMenu;
use think\facade\Cache;

class RoleService
{
    public static function getMenuAndUpdateAuth($adminId)
    {
        $adminModel = new Admin();
        $adminMenuModel = new AdminMenu();

        $admin = $adminModel->getAdmin(['id' => $adminId], ['role'])['data'];

        // 缓存权限数据
        $role = $admin['role']->toArray();

        if (empty($role)) {
            $auth = [];
        } else {
            $roleIds = array_column($role, 'id');
            if (in_array(1, $roleIds)) {
                $auth = $adminMenuModel->getAllAdminMenu(['seller_id' => $admin['seller_id'], 'status' => 1])['data']->toArray();
            } else {
                $menuIds = array_column($role, 'auth');
                $tmpMenuIds = [];
                foreach ($menuIds as $menuId) {
                    $tmp = explode(',', $menuId);
                    $tmpMenuIds = array_merge($tmpMenuIds, $tmp);
                }
                $whereIn = array_unique($tmpMenuIds);
                $auth = $adminMenuModel->getAllAdminMenu([
                    ['id', 'in', $whereIn],
                    ['seller_id', '=', $admin['seller_id']],
                    ['status', '=', 1]
                ])['data']->toArray();
            }
        }

        $allowPath = [];
        foreach ($auth as $value) {
            $key = '/' . $value['controller'] . '/' . $value['action'];
            if (!empty($value['param'])) {
                $key .= '?' . $value['param'];
            }
            if (empty($key) || $value['status'] == 2) {
                continue;
            }
            $key = strtolower($key);
            $allowPath[$key] = 1;
        }

        Cache::set('auth_'.$admin['seller_id'].'_'.$admin['id'],$allowPath);

        $menu = [];
        foreach ($auth as $val){
            if($val['is_menu'] == 1){
                $menu[] = $val;
            }
        }
        $menu = makeTree($menu);

        return dataReturn(0, lang('获取成功'), $menu);
    }
}
